<template>
    <el-card shadow="always" style="margin: 20px;">

        <el-form class="form" :inline="true">
            <el-form-item label="角色名称">
                <el-input v-model="roleName" style="width: 240px" placeholder="请输入用户名" />
            </el-form-item>

            <!-- 按钮也可以放在表单项里面 -->
            <el-form-item>
                <el-button type="primary" @click="search" :disabled="roleName?false:true">查询</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <el-card style="max-width: 100%;margin: 20px;">
        <div style="margin-bottom: 10px;">


            <el-button type="primary" @click="showPop">添加角色</el-button>

        </div>
        <el-table :data="userArr" border style="width: 100%" ref="tableRef">
            <!-- <el-table-column type="selection" width="40 " /> -->
            <el-table-column type='index' label="#" width="60" />
            <el-table-column prop="id" label="id" width="140" />
            <el-table-column prop="roleName" label="角色名称" width="160" />
            <el-table-column prop="createTime" label="创建时间" width="160" />
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" min-width="120">
                <template #="scope">
                    <el-button size="small" type="primary" :icon="Edit" @click="showRole(scope.row)">分配权限
                        <!-- @click="handleClick" -->
                    </el-button>
                    <el-button size="small" type="primary" :icon="Edit" @click="updatePop(scope.row)">编辑
                        <!-- @click="handleClick" -->
                    </el-button>
                    <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" icon-color="#626AEF"
                        title="Are you sure to delete this?" @cancel="cancelEvent"
                        @confirm="handleDelete(scope.row.id)">
                        <template #reference>
                            <el-button size="small" type="primary" :icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="pageNo" v-model:page-size="limit" :page-sizes="[4,8 , 12, 16]"
            :background="true" layout=" prev, pager, next, jumper,->,sizes,total" :total="total"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        <!-- 新增修改对话框 -->
        <el-dialog v-model="dialogVisible" :title="roleParams.id?'修改职位':'添加职位'" width="500">
            <el-form :model="roleParams" ref="ruleFormRef" :rules="rules">
                <el-form-item label="职位名称" prop="roleName">
                    <el-input v-model="roleParams.roleName"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmClick">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>



        <el-drawer v-model="roleDrawer" title="分配权限" :direction="direction">
            <template #="scope">
                <el-tree ref="tree" style="max-width: 600px" :data="data" show-checkbox node-key="id"
                    :default-expanded-keys="[2, 3]" :default-checked-keys="checkNodes" :props="defaultProps"
                    :default-expand-all="true" />
            </template>
            <template #footer>
              
                    <div style="flex: auto">
                        <el-button @click="drawer=false">取消</el-button>
                        <el-button type="primary" @click="confirmRole">确认</el-button>
                    </div>
               
            </template>

        </el-drawer>
    </el-card>
</template>
<script setup name="role" lang="ts">
    import { ref, onMounted, reactive, nextTick } from 'vue'
    import { reqRoleList, reqAddOrUpdateRole, reqRemoveRole, reqMenu, reqPermission } from '@/api/acl/role/index.ts'

    import { Edit, Delete } from '@element-plus/icons-vue'
    import { ElMessage, ElMessageBox } from 'element-plus'
    let roleName = ref('')
    let pageNo = ref(1)
    //每一页展示多少条数据
    let limit = ref(5)
    let total = ref(0)
    let userArr = ref([])
    let roleParams = reactive({
        roleName: '',
        permissionId:[]
    })
    //控制抽屉的方向
    let direction = ref('rtl')
    let drawer = ref(false)
    const checkAll = ref(false)
    const isIndeterminate = ref(true)
    //这个是添加修改用户表单的实例
    let ruleFormRef = ref()
    const userRole = ref([])
    const allRoles = ref([])
    //放置批量删除的数组
    const selectArr = ref([])
    const tableRef = ref()
    //对话框可见否
    const dialogVisible = ref(false)
    const defaultProps = {
        children: 'children',
        label: 'name',
    }
    const data = ref([])
    const checkNodes = ref([])
    const tree = ref()
    onMounted(
        () => {
            reqRole();
        }
    )
    const handleCheckAllChange = (val: boolean) => {
        // val代表全选按钮状态
        userRole.value = val ? allRoles.value : []
        isIndeterminate.value = false
    }
    const handleCheckedRoleChange = (value: any) => {

        Object.assign(userRole, value)
        // value代表勾选的内容
        const checkedCount = value.length
        checkAll.value = checkedCount === allRoles.value.length
        isIndeterminate.value =
            checkedCount > 0 && checkedCount < allRoles.value.length
    }

    const rules = reactive({
        roleName: [
            { required: true, trigger: 'blur' },

        ]
    })
    let roleDrawer = ref(false)


    const reqRole = async () => {

        let res = await reqRoleList(pageNo.value, limit.value, roleName.value)

        userArr.value = res.data.records
        total.value = res.data.total
    }
    const handleSizeChange = () => {
        pageNo.value = 1
        reqRole()
    }
    const handleCurrentChange = () => {
        reqRole()
    }
    //新增和修改操作
    const showDrawer = () => {
        drawer.value = true
        roleParams.username = ''
        roleParams.password = ''
        roleParams.name = ''
        roleParams.id = undefined
        nextTick(() => {
            // 在打开这个对话框时，form这个dom结构还没有出现
            ruleFormRef.value.clearValidate('roleName')

        })

    }
    const showPop = () => {

        dialogVisible.value = true;
        roleParams.id = 0
        roleParams.roleName = ''
        nextTick(() => {
            // 在打开这个对话框时，form这个dom结构还没有出现
            ruleFormRef.value.clearValidate('roleName')

        })
    }
    const updatePop = (row) => {
        dialogVisible.value = true;
        Object.assign(roleParams, row)
        nextTick(() => {
            // 在打开这个对话框时，form这个dom结构还没有出现
            ruleFormRef.value.clearValidate('roleName')

        })
    }


    const cancelEvent = () => {
        ElMessage({
            type: 'info',
            message: '取消删除'
        })

    }
    const confirmClick = async () => {
        await ruleFormRef.value.validate()
        let res = await reqAddOrUpdateRole(roleParams)
        if (res.code === 200) {
            reqRole()
            ElMessage({
                type: "success",
                message: roleParams.id ? '修改成功' : '添加成功'
            })
            dialogVisible.value = false
        } else {
            ElMessage({
                type: "error",
                message: roleParams.id ? '修改失败' : '添加失败'
            })
        }
    }

    const showRole = async (row) => {
        roleDrawer.value = true;
        Object.assign(roleParams, row)

        let res = await reqMenu(row.id)

        data.value = res.data
        checkNodes.value = collectSelectedIds(data.value, []);
        console.log(checkNodes.value);
    }
    const updateUser = (row) => {
        drawer.value = true;
        Object.assign(roleParams, row)

    }
    const confirmRole = async () => {
        //这2个是组件的方法
        let arr = tree.value.getCheckedKeys()
        let arr2 = tree.value.getHalfCheckedKeys()
         let permissionId = arr.concat(arr2);
        console.log(permissionId);

        let res = await reqPermission(roleParams.id, permissionId)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '分配权限成功'
            })
            reqRole()
            roleDrawer.value = false
        } else {
            ElMessage({
                type: 'error',
                message: '分配权限失败'
            })
        }
    }
    const handleDelete = async (id) => {
        let res = await reqRemoveRole(id)
        if (res.code === 200) {
            ElMessage({
                type: 'success',
                message: '删除成功'
            })
            reqRole(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
        } else {
            ElMessage({
                type: 'error',
                message: '删除失败'
            })
        }
    }



    const search = () => {
        reqRole();
        roleName.value = ''

    }
    const reset = () => {
        reqRole();
    }
    // 递归函数，遍历树并收集所有 select 为 true 的节点的 id
    const collectSelectedIds = (all, initArr) => {

        all.forEach((item) => {
            //递归出口

            if (item.level == 4 && item.select) {
                initArr.push(item.id)

            }
            //什么条件可以继续递归
            if (item.children && item.children.length > 0) {
                collectSelectedIds(item.children, initArr)

            }
        }
        )

        return initArr

    }


// 调用函数并输出结果


</script>
<style scoped lang='scss'>
    .form {
        display: flex;
        justify-content: space-between;
    }
</style>